import 'package:flutter/material.dart';
import 'package:hello_flutter/base/index.dart';

class ScrollListenAndControlWidget extends BasePage {
  const ScrollListenAndControlWidget({super.key});

  @override
  String getPageTitle() => '滚动监听与控制';

  @override
  Widget buildBody(BuildContext context) => _ScrollListenAndControlRoute();
}

class _ScrollListenAndControlRoute extends StatefulWidget {
  @override
  _ScrollListenAndControlRouteState createState() =>
      _ScrollListenAndControlRouteState();
}

class _ScrollListenAndControlRouteState
    extends State<_ScrollListenAndControlRoute> {
  final ScrollController _controller = ScrollController();
  bool showBackToTopBtn = false;
  double _progress = 0;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      // print(_controller.offset);
      if (_controller.offset < 1000 && showBackToTopBtn) {
        setState(() {
          showBackToTopBtn = false;
        });
      } else if (_controller.offset >= 1000 && !showBackToTopBtn) {
        setState(() {
          showBackToTopBtn = true;
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          LinearProgressIndicator(
            value: _progress,
            backgroundColor: Colors.grey,
            color: Colors.green,
            minHeight: 5,
          ),
          Expanded(
            child: Scrollbar(
              controller: _controller,
              child: NotificationListener<ScrollNotification>(
                onNotification: (ScrollNotification notification) {
                  setState(() {
                    _progress = notification.metrics.pixels / notification.metrics.maxScrollExtent;
                  });
                  return false;
                },
                child: ListView.builder(
                  key: const PageStorageKey(1),
                  itemCount: 100,
                  itemExtent: 50,
                  controller: _controller,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text('$index'),
                      tileColor:
                      index % 2 == 0 ? Colors.green.withOpacity(0.1) : null,
                    );
                  },
                ),
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: showBackToTopBtn
          ? FloatingActionButton(
              onPressed: () {
                _controller.animateTo(
                  0,
                  duration: const Duration(milliseconds: 200),
                  curve: Curves.ease,
                );

                // _controller.jumpTo(0);
              },
              shape: const CircleBorder(),
              child: const Icon(Icons.arrow_upward),
            )
          : null,
    );
  }
}
